// ignore_for_file: file_names, slash_for_doc_comments, must_call_super, unnecessary_overrides, override_on_non_overriding_member, must_be_immutable, prefer_const_constructors, sized_box_for_whitespace, avoid_unnecessary_containers, avoid_print

import 'package:desktop_webview_window/desktop_webview_window.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:webview_window_example/config/ConfigVal.dart';
import 'package:webview_window_example/pages/androidUpdateXml/AndroidUpdateXmlPage.dart';
import 'package:webview_window_example/entity/TranslateEntity.dart';

import 'dart:async';
import 'dart:io';

import 'package:mybase/base/tool/empty/FFEmpty.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';

import 'package:crypto/crypto.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mybase/base/tool/file/FFile.dart';
import 'dart:convert';

import 'package:webview_window_example/pages/appleUpdateTxt/AppleUpdateTxtPage.dart';
import 'package:webview_window_example/utils/CommonUtils.dart';

extension AppleUpdateTxtEvent on AppleUpdateTxtPageState {
  ///开始
  void onStart() async {
    if (FFEmpty.stringIsEmpty(textController.text)) {
      SmartDialog.showToast("待翻译的值不能为空啊");
      return;
    }

    webview = await WebviewWindow.create(
      configuration: CreateConfiguration(
          userDataFolderWindows: await _getWebViewPath(),
          titleBarTopPadding: Platform.isMacOS ? 20 : 0,
          windowWidth: 600,
          windowHeight: 600),
      iWebview: this,
    );

    TranslateEntity entity = entitys[selectIndex];

    webview
      ..setBrightness(Brightness.dark)
      ..launch(getUrl(entity.urlCode, Uri.encodeFull(textController.text)))
      ..addOnUrlRequestCallback((url) {
        debugPrint('snjj addOnUrlRequestCallback = $url');
      })
      ..addOnWebMessageReceivedCallback((message) {
        print("snjj addOnWebMessageReceivedCallback = $message");
      })
      ..onClose.whenComplete(() {
        debugPrint("snjj whenComplete");
      });
  }

  onNext() {
    selectIndex++;
    if (selectIndex >= entitys.length) {
      selectIndex = 0;
    }
    setState(() {});
  }

  onAdd() {
    if (FFEmpty.stringIsEmpty(resultController.text)) {
      SmartDialog.showToast("结果为空啊", displayTime: Duration(milliseconds: 250));
      return;
    }

    TranslateEntity entity = entitys[selectIndex];
    entity.translatedValue = resultController.text;
    SmartDialog.showToast("加入成功", displayTime: Duration(milliseconds: 250));
  }

  onReStartAutoTranslate() async {
    selectIndex = 0;
    setState(() {});
    SmartDialog.showToast("现在开始", displayTime: Duration(milliseconds: 250));
    await Future.delayed(Duration(milliseconds: 250));
  }

  Future<String> _getWebViewPath() async {
    final document = await getApplicationDocumentsDirectory();
    String path = p.join(
      document.path,
      'desktop_webview_window',
    );
    print("path = $path");
    return path;
  }

  //提取翻译文字
  extractTranslate() async {
    String? value;
    try {
      String js = """
function ycss() {
    var str = "";
    var array = document.getElementsByClassName('ryNqvb');
    for (let index = 0; index < array.length; index++) {
        const element = array[index];
        str =  str + element.innerHTML;
     }
    return str;
 }

ycss();
      """;

      value = await webview.evaluateJavaScript(js);

      ///如果没有，极有可能是有多个翻译的情况
      if (FFEmpty.stringIsEmpty(value)) {
        js = """
function ycss() {
    var str = "";
    var array = document.getElementsByClassName('HwtZe');
    for (let index = 0; index < array.length; index++) {
        const element = array[index];
        str =  str + element.innerHTML;
        break;
     }
    return str;
 }

ycss();
      """;

        value = await webview.evaluateJavaScript(js);
      }
    } catch (e) {
      debugPrint('evaluateJavaScript error: $e');
    }

    if (FFEmpty.stringIsEmpty(value)) {
      // didFinished(0);
      SmartDialog.showToast("出现问题，请注意",
          displayTime: Duration(milliseconds: 1000));
      return;
    }

    // ///如果是德语，转换双引号
    // TranslateEntity entity = entitys[selectIndex];
    // if (entity.code == "de") {
    //   value = value!.replaceAll("“", "\"");
    //   value = value!.replaceAll("„", "\"");
    // }
    //
    // ///如果右括号左边就是逗号，则去掉
    // int index = value!.lastIndexOf(",");
    // print("index = $index   ,,, lenth = ${value.length}");
    // if (value.length - index <= 5) {
    //   value = value.replaceRange(index, index + 1, "");
    // }

    resultController.text = value!;
    webview.close();
  }

  //校验翻译的合法性
  bool checkTranslate(String text) {
    bool ok = false;
    try {
      Map<String, dynamic> md5Map = json.decode(text);
      ok = true;
    } catch (e) {
      print("解析出错了");
    }

    return ok;
  }

  onClickWrite() async {
    if (FFEmpty.stringIsEmpty(targetDir)) {
      SmartDialog.showToast("目标目录为空");
      return;
    }

    write();
  }

  onSelectTargetFile() async {
    String? selectedDirectory = await FilePicker.platform
        .getDirectoryPath(initialDirectory: ConfigVal.desktopDir);

    if (FFEmpty.stringIsEmpty(selectedDirectory)) {
      SmartDialog.showToast("目标目录选择失败");
      return;
    }

    targetDir = selectedDirectory;
    setState(() {});
  }

  Future<void> write() async {
    String fileName = "mytxt.txt";
    String targetFile = "${targetDir}/$fileName";

    if (!(await FFile.isExistFile(targetFile))) {
      File? file = await FFile.createFile(targetFile);
      if (file == null) {
        SmartDialog.showToast("创建文件: 失败");
      }
    }

    List<TranslateEntity> addList = [
      TranslateEntity(
          code: "",
          title: "英语",
          urlCode: "",
          translatedValue: textController.text),
    ];
    addList.addAll(entitys);

    String result = "";
    for (int i = 0; i < addList.length; i++) {
      TranslateEntity entity = addList[i];
      if (!FFEmpty.stringIsEmpty(entity.translatedValue)) {
        String current = """
>>>>>>>>
>>>>>>>>
>>>>>>>>
>>>>>>>>
>>>>>>>>        

<<${entity.title}>>
${entity.translatedValue}
""";
        result = "${result}\n${current}";
      }
    }

    bool success = await FFile.writeContentByPath(
        filePath: targetFile, content: result, mode: FileMode.write);
    SmartDialog.showToast("写入状态: $success");
  }
}
